package kr.hkit.androidcomplete03.ch28;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import kr.hkit.androidcomplete03.R;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class DownloadManagerEx extends Activity {
	DownloadManager DM;
	long mld = 0;
	ImageView image;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch28_downmanager);
		image = (ImageView) findViewById(R.id.ch28_downmanager_image);

	}

	BroadcastReceiver mDownComplete = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			Toast.makeText(context, "다운로드 완료", 0).show();
		}
	};

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (mld != 0) {
			unregisterReceiver(mDownComplete);
		}
	}

	public void mOnClick(View v) {
		switch (v.getId()) {
		case R.id.ch28_downmanager_btnqueue:
			Uri uri = Uri
					.parse("http://developer.android.com/images/home/kk-hero.jpg");
			DownloadManager.Request req = new DownloadManager.Request(uri);
			req.setTitle("테스트 다운로드");
			req.setDescription("이미지 파일을 다운로드 받습니다.");
			req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI
					| DownloadManager.Request.NETWORK_MOBILE);

			mld = DM.enqueue(req);

			IntentFilter filter = new IntentFilter();
			filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

			registerReceiver(mDownComplete, filter);
			break;

		case R.id.ch28_downmanager_btnview:

			try {
				ParcelFileDescriptor file;
				file = DM.openDownloadedFile(mld);
				FileInputStream fis = new ParcelFileDescriptor.AutoCloseInputStream(
						file);
				Bitmap bm = BitmapFactory.decodeStream(fis);
				image.setImageBitmap(bm);
			} catch (FileNotFoundException e) {
				Toast.makeText(this, "파일이 없음", 0).show();
			}
			break;
			
		case R.id.ch28_downmanager_btndelete:
			if(DM.remove(mld) == 1){
				Toast.makeText(this, "삭제완료", 0).show();
				image.setImageBitmap(null);
			}
			
			break;
		}//end of switch
	}//end of mOnClick()
}//end of class
